/**
 * @title
 * @description
 * @author 张玉华
 * @date 2020-11-17 09:39
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, Repository } from 'typeorm';
import { Order } from '../../entity/Order';

@Injectable()
export class OrderService {
  constructor(
    private readonly connection: Connection,
    @InjectRepository(Order) private readonly OrdersRepository: Repository<Order>) {

  }

  findAll(): Promise<Order[]> {
    return this.OrdersRepository.find();
  }

  save(order: Order){
    return this.OrdersRepository.save(order);
  }

  findOne(id: string): Promise<Order> {
    return this.OrdersRepository.findOne(id);
  }

  async remove(id: string): Promise<void> {
    await this.OrdersRepository.delete(id);
  }

  // 使用事务
  async createMany(orders: Order[]) {
    const queryRunner = this.connection.createQueryRunner();

    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      await queryRunner.manager.save(orders[0]);
      await queryRunner.manager.save(orders[1]);

      await queryRunner.commitTransaction();
    } catch (err) {
      // since we have errors lets rollback the changes we made
      await queryRunner.rollbackTransaction();
    } finally {
      // you need to release a queryRunner which was manually instantiated
      await queryRunner.release();
    }
  }

}
